package com.winit.needcustomers.web;


import com.winit.common.base.web.BaseController;
import com.winit.needcustomers.model.NeedCustomer;
import com.winit.needcustomers.task.FetchCustomersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Api(value = "need", tags = {"needCustomer"}, description = "needCustomer")
@RestController
@RequestMapping("/api/v1/needcustomer")
public class NeedCustomerController extends BaseController {

    private static Logger log = LoggerFactory.getLogger(NeedCustomerController.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private FetchCustomersService fetchCustomersService;

    @RequestMapping(value = "/getCustomers", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "从缓存中去获取客户信息")
    public Object getNeedCustomers() {
        List<NeedCustomer> result = null;
        try {
            result = (List<NeedCustomer>) redisTemplate.opsForValue().get("needCustomer");
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            System.err.println(e);
        }
        if (result == null || result.size() == 0) {
            return this.getRtn("1", "fail");
        } else {
            return this.getRtn("0", "success", result);
        }
    }

    @RequestMapping(value = "/handGetCustomers", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "手动刷新缓存")
    public Object handGetCustomers() {
        List<NeedCustomer> result = null;
        try {
            fetchCustomersService.flushAndLoadCustomers();
            return this.getRtn("0", "success");
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            System.err.println(e);
            return this.getRtn("1", "fail");
        }
    }

}
